var express = require('express');
var home_router = express.Router();
var db = require('../models')
const Op = require('sequelize').Op;

//客户端获取最新上架图片
home_router.get('/getNew', async (req, res) => {
  var {page=1,pagesize=12}=req.body
  var condition={
      where: {is_enable:0},
      raw: true, 
      offset: pagesize * (page - 1),
      limit: parseInt(pagesize),
      order:[['create_time', 'DESC']]
  }
  var imgList = await db.images.getList(condition)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  imgList.code = 200
  res.json(imgList)
});


home_router.get('/getSearchBar', async (req, res) => {
  let list = await db.search_bar.getSearchBar({status:0})
  let data = {
      code: 200,
      rows: list
  }
  res.json(data)

});

// 获取热门专题
home_router.get('/getHot', async (req, res) => {
  var [page = 1, pagesize = 4] = [req.query.pageNo, req.query.pageSize]
  let condition = { pagesize, "page": page}
  condition.where={status:0}
  let topic = await db.special_topic.getHotTopics(condition)
  let data = {
      code: 200,
      rows: topic
  }
  res.json(data)
});


home_router.get('/getRecommend', async (req, res) => {
  let categorys = await db.recommend_category.getRecommend()
  let data = {
    code: 200,
    rows: categorys
  }
  res.json(data)
});

// 客户端首页获取TopList排行图片
home_router.post('/getTopImageList', async (req, res) => {
  var [page = 1, pagesize = 12, userid=null,favorite_type=0] = [req.body.page, req.body.pageSize, req.body.userid,req.body.favorite_type]
  // var [userid,favorite_type=0] = [req.body.userid,req.body.favorite_type]
  let condition = {
    "pagesize": pagesize,
    "page": page,
    where: {is_enable:0},
    order: [['download_counts', 'DESC']]
  }
  var imgList = await db.images.getList(condition)
  if (userid !== '' && userid !== null) {
    let pars = {};
    pars.uid = userid
    pars.favorite_type=favorite_type
    for (var o of imgList.rows) {
      pars.image_id = o.id
      let isCollect = await db.userFavorites.checkUserCollect(pars);
      o.isCollect = isCollect
    }
  } else {
    for (var y of imgList.rows) {
      y['isCollect'] = '';
    }
  }
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  imgList.code = 200
  res.json(imgList)
})

//客户端获取首页热门Top排行图片列表
home_router.post('/getTopHotImageList', async (req, res) => {
  var [page = 1, pagesize = 12, userid=null] = [req.body.page, req.body.pageSize, req.body.userid]
  let condition = {
    "pagesize": pagesize,
    "page": page
  }
  var imgList = await db.images.getMostHot(condition)
  if (userid !== '' && userid !== null) {
    for (var o of imgList.rows) {
      let pars = {};
      pars.image_id = o.id
      pars.uid = userid
      let isCollect = await db.userFavorites.checkUserCollect(pars);
      o.isCollect = isCollect
    }
  } else {
    for (var y of imgList.rows) {
      y['isCollect'] = '';
    }
  }
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  imgList.code = 200
  res.json(imgList)
})
// 根据关键词keyWords获取所有图片
home_router.post('/getImgList', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var { keyWords = null } = req.body.queryData
  var tagIds = [], categoryIds = []
  let tagList = await db.tag.getTagByName(keyWords)
  for (let item of tagList) {
    tagIds.push(item.id)
  }
  let categoryList = await db.category.getCategoryByName(keyWords)
  for (let item of categoryList) {
    categoryIds.push(item.id)
  }
  var pars = {
    tagIds: tagIds,
    categoryIds: categoryIds,
    page: page,
    pagesize: pagesize
  }
  var imgList = await db.images.getListByKeyWords(pars)
  if(imgList.rows.length>0){
    for (let r of imgList.rows) {
      r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
      delete r.oss_prepath
      delete r.prefix_path
    }
  }
  res.json(imgList)
})
/**
 * 图片相关
 */
home_router.post('/getImageLikely', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var { category_id = null, tag_id = null } = req.body.queryData
  var pars = {
    page: page,
    pagesize: pagesize,
    category_id: category_id,
    tag_id: tag_id
  }
  var imgList = await db.images.getImagesLikely(pars)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  res.json(imgList)
})
/**
 * 根据标签ID获取
 */
home_router.post('/getImageByTag', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var { tag_id = null } = req.body.queryData
  var pars = {
    tag_id: tag_id,
    page: page,
    pagesize: pagesize
  }
  var imgList = await db.images.getImagesByTagId(pars)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  res.json(imgList)
})
/**
 * 根据分类ID获取
 */
home_router.post('/getImageByCategory', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var { category_id } = req.body.queryData
  var condition = { page: page, pagesize: pagesize }
  var where = {
    category: category_id,
    is_enable: 0
  }
  condition.where = where
  condition.order = [['download_counts', 'DESC']]
  var imgList = await db.images.getList(condition)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  res.json(imgList)
})

/**
 * 根据专题ID获取
 * @param {*} pars 
 */
home_router.post('/getImgListByTopic', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var { topic_id = null } = req.body.queryData
  add_topic_wacth_num(topic_id)
  var assId = await db.topic_relation.gettopicInner(topic_id)
  var topic = await db.topic.getTopicById(topic_id)
  var imgList = []
  if (topic.tp_type === 1) {
    var condition = { page: page, pagesize: pagesize }
    var where = {
      category: assId[0].associated_id,
      is_enable: 0
    }
    condition.where = where
    condition.order = [['download_counts', 'DESC']]
    var imgList = await db.images.getList(condition)
    for (let r of imgList.rows) {
      r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
      delete r.oss_prepath
      delete r.prefix_path
    }
  } else if (topic.tp_type === 2) {  //根据多个标签
    var tags = []
    for (let item of assId) {
      tags.push(item.associated_id)
    }
    var pars = {
      tagIds: tags,
      page: page,
      pagesize: pagesize
    }
    imgList = await db.images.getImagesByTags(pars)
    for (let r of imgList.rows) {
      r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
      delete r.oss_prepath
      delete r.prefix_path
    }
  } else if (topic.tp_type === 3) {   //根据图片ID
    var imgIds = []
    for (let item of assId) {
      imgIds.push(item.associated_id)
    }
    var pars = {
      imgIds: imgIds,
      page: page,
      pagesize: pagesize
    }
    imgList = await db.images.getListByImgIds(pars)
    for (let r of imgList.rows) {
      r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
      delete r.oss_prepath
      delete r.prefix_path
    }
  }
  if(topic!==null) imgList.topicDetail = topic
  res.json(imgList)

})

/**
 * 获取最新图片
 */
home_router.post('/getNewImg', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.body.page, req.body.pagesize]
  var condition = {}
  var where = {
    is_enable: 0
  }
  condition.where=where
  condition.order = [
    ['create_time', 'DESC']
  ]
  imgList = await db.images.getList(condition)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  res.json(imgList)
})
// 客户端根据一张图片详情
/**
 * @author: xgq
 * @description: 
 * @param {type} 
 * @return: 
 */
home_router.post('/getDetails',async (req, res)=>{
  var [image_id,uid=null]=[req.body.id,req.body.uid]
  var pars={is_enable:0,id:image_id}
  let result = await db.images.getDetailsById(pars)
  let addWatchNum = await db.images.update({
    watch_num: db.images.sequelize.literal('watch_num + 1')
  }, {
    'where': {
      'id': image_id
    }
  })
  let collect_num = await db.userFavorites.getCollectCountByid(image_id)
  let categoryName = await db.category.getCategoryNameById(result.category)
  if(uid!==null&&uid!==''){
    let p={image_id,uid}
    let isCollect=await db.userFavorites.checkUserCollect(p)
    result.isCollect=isCollect
  }else{
    result.isCollect=''//表示未登录
  }
  result.categoryName=categoryName.name
  result.collect_num = collect_num;
  result.img_thumbnail = `${result.oss_prepath}${result.prefix_path}_${result.img_thumbnail}`
  result.addWatchNum = addWatchNum;
  res.json(result)
})


 
/**
 * @author: xgq
 * @description: 客户端收藏图片
 * @param {type} 
 * @return: 
 */
home_router.post('/collectPicture',async (req, res)=> {
  var pars = req.body;
  // let user_id = req.body.uid;
  var result = await db.userFavorites.checkUserCollect(pars);
  if (result) {
      var collect = await db.userFavorites.deleteCollect(pars);
      res.json({
          code: -1,
          msg: '取消收藏',
          sel: result,
          update: collect
      })
  } else {
      var r = await db.userFavorites.pushCollect(pars);
      res.json({
          code: 1,
          msg: '已收藏',
          sel: result,
          update: r
      })
  }
})
/**
 * @author: xgq
 * @description: 客户端收藏图片
 * @param {type} 
 * @return: 
 */
home_router.post('/favoritesIcon',async (req, res)=> {
  let create_time=parseInt(new Date().getTime()/1000);
  var favorite_type=2
  var img_id=req.body.icon_id
  var user_id = req.body.uid;
  db.userFavorites.findCreateFind({
    where: {img_id,user_id,favorite_type}, 
    defaults: {img_id,user_id,favorite_type,create_time}
  })
  .spread((user, created) => {
    if(created === false) {
      db.userFavorites.destroy({
        where:{user_id,img_id,favorite_type}
      }).then(result=>{
        res.json({
                  code: -1,
                  msg: '取消收藏',
                  sel: user,
                  update: created
              })
      })
    }else{
      res.json({
                code: 1,
                msg: '已收藏',
                sel: user,
                update: created
            })
    }
  })
})
/**
 * @author: xgq
 * @description: 
 * @param {type} 
 * @return: 
 */
home_router.post('/guessYourLike',async (req, res)=> {
  var pars = req.body;
  // let user_id = req.body.uid;
  let {
    page = 1, pageSize = 12, userId
  } = pars
  let condition = {
      "pagesize": pageSize,
      "page": page,
      where:{is_enable:0},
      order:[['download_counts', 'DESC'],['watch_num', 'DESC'],['like_num','DESC'],['create_time', 'DESC']]
  }
  var imgList = []
  var images=[]
  let images_like = await db.userBehavior.getImageIdByUid(userId);//获取用户点赞过的图片
  let image_down = await db.userDownloads.getImageIdByUid(userId);//获取用户下载过的图片
  let images_favorites = await db.userFavorites.getImageIdByUid(userId);//获取用户收藏过的图片
  images=images.concat(images_like,image_down,images_favorites)
  if (images.length > 0) {
      var len=images.length;
      var arr=[]
      for(let i = 0; i < len; i++) {
          arr[i]=await db.tagImage.getTagByImgId(images[i].img_id);
      }
      var arrlen=arr.length;
      var tagIds=[]
      for(let j=0;j<arrlen;j++){
          for(let m=0;m<arr[j].length;m++){
              tagIds.push(arr[j][m].tag_id)
          }
      }
      var mostTagId=findMost(tagIds)
      condition.tag_id=mostTagId
    }
    imgList = await db.images.getListTags(condition)
    for (let r of imgList.rows) {
        r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
        delete r.oss_prepath
        delete r.prefix_path
    }
 
  imgList.code = 200
  res.json(imgList)
})

function findMost (arr) {
  if (!arr.length) return;
  if (arr.length === 1) return 1;
  let res = {};
  let maxName, maxNum = 0
  // 遍历数组
  arr.forEach((item) => {
    res[item] ? res[item] += 1 : res[item] = 1
    if (res[item] > maxNum) {
      maxName = item
      maxNum = res[item]
    }
  })
  return maxName;
}  


home_router.post('/likePicture',async (req, res)=> {
  var pars = req.body;
    let user_id = req.body.uid;
    let img_id = req.body.image_id
    var behavior_type=0
    pars.behavior_type=behavior_type
    let create_time=parseInt(new Date().getTime()/1000);
    var result = await db.userBehavior.checkUserLike(pars);
    if (result) {
      //删除用户与图片的关系
      let r = await db.images.sequelize.transaction(t => {
        return db.userBehavior.destroy({
          where: {
            "img_id": img_id,
            "user_id": user_id,
            "behavior_type": 0
          },
          transaction: t
        }).then(user => {
          return db.images.update({
            like_num: db.images.sequelize.literal('like_num - 1')
          }, {
            where: {
              "id": img_id,
            },
            transaction:t
          })
        });
      }).then(result => {
        return result
      }).catch(err => {
        return null
      })
      res.json({
        code: -1,
        msg: '已经取消点赞',
        data: r
      })
    } else {
      var queryData = await db.images.sequelize.transaction(t => {
        return db.images.update({
            like_num: db.images.sequelize.literal('like_num + 1')
          }, {
            'where': {
              'id': img_id
            },
            transaction: t
          })
          .then(user => {
            return db.userBehavior.create({
              img_id,
              user_id,
              behavior_type,
              create_time
            }, {
              transaction: t
            })
          })
      });
      res.json({
        code: 1,
        msg: '点赞成功',
        data: queryData
      })
    }
})


/**
 * @author: xgq
 * @description: 根据用户id，图片id,获取用户是否收藏图片
 * @param {type} 
 * @return: 
 */
home_router.post('/checkUserCollectStatus',async (req, res)=>{
    var pars = req.body;
    var result = await db.userFavorites.checkUserCollect(pars);
    res.json(result)
})

/**
 * @author: xgq
 * @description: 图片下载量+1
 * @param {type} 
 * @return: 
 */
home_router.post('/add_download_counts',async (req, res)=>{
    let user_id = req.body.uid;
    let img_id = req.body.image_id
    let down_type=req.body.down_type
    let down_size=req.body.down_size
    let down_format=req.body.down_format
    let create_time=parseInt(new Date().getTime()/1000);
    var queryData = await db.images.sequelize.transaction(t => {
      return db.images.update({
          download_counts: db.images.sequelize.literal('download_counts + 1')
        }, {
          'where': {
            'id': img_id
          },
          transaction: t
        })
        .then((data)=>{
          return db.user.update({
            downloads: db.user.sequelize.literal('downloads + 1')
          }, {
            'where': {
              'id': user_id
            },
            transaction: t
          })
        })
        .then(user => {
          return db.userDownloads.findCreateFind({where:{img_id,user_id},
            defaults:{
              img_id,
              user_id,
              down_type,
              down_size,
              down_format,
              create_time
            },
            transaction: t})
            
        })
    });
    res.json({
      code: 1,
      msg: '已更新下载数',
      data: queryData
    })
})

// 专题热度值+1
var add_topic_wacth_num=(topic_id)=>{
  db.topic.update({
    watch_num: db.images.sequelize.literal('watch_num + 1')
  }, {
    'where': {
      'id': topic_id
    }
  })
}

// 获取下载过的图片
home_router.post('/getDownloadByUid',async (req, res)=>{
  let{page=1,pagesize=15,userid}=req.body
  // let condition = {
  //   distinct: true,
  //   "pagesize": pagesize,
  //   "page": page,
  //   offset: pagesize * (page - 1),
  //   limit: parseInt(pagesize),
  //   include:[
  //     {
  //       model:db.userDownloads,
  //       attributes: ['img_id'],
  //     }
  //   ]
  // }
  var par={user_id:userid,order:[['create_time', 'DESC']],offset: pagesize * (page - 1),limit:parseInt(pagesize), "pagesize": pagesize,
  "page": page}
  let imgList=await db.userDownloads.getImageIdByUidInOrder(par)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  imgList.code = 200
  res.json(imgList)
})

// 获取收藏过的图片
home_router.post('/getMyCollect',async (req, res)=>{
  let{page=1,pagesize=15,userid}=req.body
  var par={user_id:userid,order:[['create_time', 'DESC']],offset: pagesize * (page - 1),limit:parseInt(pagesize), "pagesize": pagesize,
  "page": page}
  let imgList=await db.userFavorites.getImageIdByUidInOrder(par)
  for (let r of imgList.rows) {
    r.img_thumbnail = `${r.oss_prepath}${r.prefix_path}_${r.img_thumbnail}`
    delete r.oss_prepath
    delete r.prefix_path
  }
  imgList.code = 200
  res.json(imgList)
})

home_router.post('/getIconList', async (req, res) => {
  var pars={}
  var where={is_enable:0};
  pars.where=where;
  var iconList = await db.icons.getAllIcons(pars)
  iconList.code = 200
  res.json(iconList.rows)
});


function unique(arr){
  var hash=[];
  for (var i = 0; i < arr.length; i++) {
     if(hash.indexOf(arr[i])==-1){
      hash.push(arr[i]);
     }
  }
  return hash;
}

module.exports = home_router